package com.component.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.component.domain.Content;
import com.component.enumitem.NoteDataTypeEnum;
import com.component.mapper.ContentMapper;
import com.component.service.ContentService;
import com.system.common.ContextUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/6 1:17
 * @since JDK 1.8
 */
@Service
@CacheConfig(cacheNames = "ContentServiceImpl")
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements ContentService {

    @Caching(
            evict = {
                    @CacheEvict(cacheNames = "content", key = "#entity.nid"),
            }
    )
    @Override
    public boolean updateById(Content entity) {
        return super.updateById(entity);
    }

    @Cacheable(cacheNames = "content",key = "#nid")
    @Override
    public Content getContentByNid(Integer nid) {
        return super.getBaseMapper().selectContentOne(nid);
    }

    @Override
    public List<Content> sumContent(String channelId) {
        List<Content> list=super.getBaseMapper().sumContent(channelId);
        if(list ==null){
            return Collections.emptyList();
        }
        for (int i = 0; i < list.size(); i++) {
            Content content = list.get(i);
            content.setContent(ContextUtils.decryptStr(content.getContent()));
        }
        return list;
    }

    @Override
    public JSONArray getModel(Content content) {
        JSONObject object=getJSONObject(content);
        if(object.containsKey("model")){
            return object.getJSONArray("model");
        }
        return new JSONArray();
    }

    @Override
    public JSONArray getArray(Content content) {
        JSONObject object=getJSONObject(content);
        if(object.containsKey("array")){
            return object.getJSONArray("array");
        }
        return new JSONArray();
    }

    public JSONObject getJSONObject(Content content){
        if(!content.getDatatype().equals(NoteDataTypeEnum.JSON.getDataType())){
            return new JSONObject();
        }
        String str=ContextUtils.decryptStr(content.getContent());
        System.out.println(str);
        JSONObject json=JSONObject.parseObject(str);
        return json;
    }
}
